package bjx.com.kehu.ui.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import bjx.com.kehu.R;
import bjx.com.kehu.adapter.MyOrderAdapter;
import bjx.com.kehu.contants.Constants;
import bjx.com.kehu.model.MyOrderModel;
import bjx.com.kehu.utils.GsonUtil;
import bjx.com.kehu.utils.LogsUtil;
import bjx.com.kehu.utils.MD5;
import cn.bingoogolapple.androidcommon.adapter.BGAOnItemChildClickListener;
import cn.bingoogolapple.refreshlayout.BGAMoocStyleRefreshViewHolder;
import cn.bingoogolapple.refreshlayout.BGARefreshLayout;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by jqc on 2017/10/25.
 */

public class MyOrderActivity extends BaseActivity implements AdapterView.OnItemClickListener, BGARefreshLayout.BGARefreshLayoutDelegate, BGAOnItemChildClickListener {

    ImageView mIVBack;
    TextView mTVTitle;
    TextView mTVEvent;

    BGARefreshLayout mRefreshLayout;
    ListView mListView;
    MyOrderAdapter mAdapter;
    RelativeLayout mRLDel;
    CheckBox mCBDelAll;
    TextView mTVDel;

    int mCurrentPage = 1;
    String pageCount = "10";

    @Override
    protected void initView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_myorder);


        mIVBack = getViewById(R.id.back);
        mTVTitle = getViewById(R.id.title);
        mTVTitle.setText("订单");
        mTVEvent = getViewById(R.id.event);
        mTVEvent.setText("编辑");
        mTVEvent.setVisibility(View.VISIBLE);

        mRLDel = getViewById(R.id.myorder_rl_del);
        mCBDelAll = getViewById(R.id.myorder_cb_delall);
        mTVDel = getViewById(R.id.myorder_tv_del);

        mRefreshLayout = getViewById(R.id.rl_myorder_refresh);
        mListView = getViewById(R.id.myorder_lv);

        BGAMoocStyleRefreshViewHolder moocStyleRefreshViewHolder = new BGAMoocStyleRefreshViewHolder(mApp, true);
        moocStyleRefreshViewHolder.setUltimateColor(R.color.red);
        moocStyleRefreshViewHolder.setOriginalImage(R.mipmap.custom_mooc_icon);
        moocStyleRefreshViewHolder.setRefreshViewBackgroundColorRes(R.color.grey_light);
        moocStyleRefreshViewHolder.setLoadMoreBackgroundColorRes(R.color.grey_light);
        moocStyleRefreshViewHolder.setSpringDistanceScale(0);
        mRefreshLayout.setRefreshViewHolder(moocStyleRefreshViewHolder);
        mRefreshLayout.setTag(false);

        mAdapter = new MyOrderAdapter(mApp, R.layout.lv_item_myorder);
        mListView.setAdapter(mAdapter);
    }

    @Override
    protected void setListener() {
        mIVBack.setOnClickListener(this);
        mTVEvent.setOnClickListener(this);
        mRefreshLayout.setDelegate(this);
        mCBDelAll.setOnClickListener(this);
        mTVDel.setOnClickListener(this);
        mListView.setOnItemClickListener(this);
        mAdapter.setOnItemChildClickListener(this);
    }

    @Override
    protected void processLogic(Bundle savedInstanceState) {
        loadOrderList();
    }

    List<String> delOrder = new ArrayList<>();

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.event: // 编辑
                if (!mAdapter.isOpen()) {
                    mRefreshLayout.setPullDownRefreshEnable(false);
                    mRefreshLayout.setTag(true);
                    delOrder.clear();
                    mTVEvent.setText("完成");
                    mAdapter.switchDel(true);
                    mRLDel.setVisibility(View.VISIBLE);
                    mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            CheckBox mCB = (CheckBox) view.findViewById(R.id.myorder_item_cb);
                            if (mCB.isChecked()) {
                                mCB.setChecked(false);
                                delOrder.remove(mAdapter.getItem(position).getOrder_id());
                            } else {
                                mCB.setChecked(true);
                                delOrder.add(mAdapter.getItem(position).getOrder_id());
                            }
                        }
                    });
                } else {
                    mRefreshLayout.setPullDownRefreshEnable(true);
                    mRefreshLayout.setTag(false);
                    mTVEvent.setText("编辑");
                    mAdapter.switchDel(false);
                    mRLDel.setVisibility(View.GONE);
                    mListView.setOnItemClickListener(this);
                }
                break;
            case R.id.myorder_cb_delall: // 全选
                if (mAdapter.isCheckAll()) {
                    mAdapter.switchCheck(false);
                    for (int i = 0; i < mAdapter.getData().size(); i++) {
                        delOrder.remove(mAdapter.getData().get(i).getOrder_id());
                    }
                } else {
                    mAdapter.switchCheck(true);
                    for (int i = 0; i < mAdapter.getData().size(); i++) {
                        delOrder.add(mAdapter.getData().get(i).getOrder_id());
                    }
                }
                break;
            case R.id.myorder_tv_del: // 删除所选
                if (delOrder.size() == 0) {
                    return;
                }

                AlertDialog.Builder builder = new AlertDialog.Builder(this).setTitle("提示")
                        .setMessage("确定要删除所选订单吗？")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                mEngine.delOrder(fmtDelOrder(), userModel.getUser_id(), MD5.getMessageDigest((fmtDelOrder() + Constants.BASE_KEY + userModel.getUser_id()).getBytes())).enqueue(new Callback<ResponseBody>() {
                                    @Override
                                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                                        try {
                                            String str = response.body().string();
                                            JSONObject jo = new JSONObject(str);
                                            int status = jo.getInt("status");
                                            String msg = jo.getString("msg");
                                            if (status == 200) {
                                                mRefreshLayout.setPullDownRefreshEnable(true);
                                                mRefreshLayout.setTag(false);
                                                mTVEvent.setText("编辑");
                                                mAdapter.switchDel(false);
                                                mRLDel.setVisibility(View.GONE);
                                                mListView.setOnItemClickListener(MyOrderActivity.this);
                                                loadOrderList();
                                                delOrder.clear();
                                                showToast("删除成功");
                                            } else if (status == 201) {
                                                showToast("用户不存在");
                                            } else if (status == 100) {
                                                showToast("删除失败");
                                            } else {
                                                showToast("删除异常");
                                            }
                                        } catch (IOException e) {
                                            e.printStackTrace();
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }
                                    }

                                    @Override
                                    public void onFailure(Call<ResponseBody> call, Throwable t) {
                                    }
                                });
                            }
                        })
                        .setNegativeButton("取消", null);
                builder.create().show();
                break;
            case R.id.back:
                finish();
                break;
            default:
                break;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        startActivity(new Intent(mApp, OrderDetailActivity.class).addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT).putExtra("orderid", mAdapter.getItem(position).getOrder_id()));
    }

    @Override
    public void onItemChildClick(ViewGroup parent, View childView, int position) {
        switch (childView.getId()) {
            case R.id.myorder_item_cb: // 单选
                CheckBox mCB = ((CheckBox) childView);
                if (!mCB.isChecked()) {
                    mCB.setChecked(false);
                    delOrder.remove(mAdapter.getItem(position).getOrder_id());
                } else {
                    mCB.setChecked(true);
                    delOrder.add(mAdapter.getItem(position).getOrder_id());
                }
                break;


            default:
                break;
        }
    }

    private void loadOrderList() {
        LogsUtil.normal("订单里面获取的 用户id" + userModel.getUser_id());

        mEngine.loadOrderList(userModel.getUser_id(), MD5.getMessageDigest((Constants.BASE_KEY +
                userModel.getUser_id()).getBytes()), String.valueOf(mCurrentPage), pageCount).
                enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                        try {
                            String str = response.body().string();
                            JSONObject jo = new JSONObject(str);
                            int status = jo.getInt("status");
                            String msg = jo.getString("msg");
                            String fid = jo.getString("fid");

                            if (status == 200) {
                                JSONArray ja = jo.getJSONArray("result");
                                List<MyOrderModel> mOrderList = new ArrayList<>();
                                for (int i = 0; i < ja.length(); i++) {
                                    mOrderList.add(GsonUtil.jsonToOrderBean(ja.getJSONObject(i).toString()));
                                }
                                mAdapter.setData(mOrderList);
                            } else if (status == 201) {
                                showToast("用户不存在");
                            } else if (status == 100) {
                                showToast("获取列表失败");
                            } else {
                                showToast("获取异常");
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable t) {
                    }
                });
    }

    private String fmtDelOrder() {
        String delOrderStr = "";
        if (delOrder != null) {
            for (int i = 0; i < delOrder.size(); i++) {
                if (i == 0) {
                    delOrderStr += delOrder.get(i);
                } else {
                    delOrderStr += "," + delOrder.get(i);
                }
            }
        }
        return delOrderStr;
    }

    @Override
    public void onBGARefreshLayoutBeginRefreshing(BGARefreshLayout refreshLayout) {
        mCurrentPage = 1;
        mEngine.loadOrderList(userModel.getUser_id(), MD5.getMessageDigest((Constants.BASE_KEY + userModel.getUser_id()).getBytes()), String.valueOf(mCurrentPage), pageCount).enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    String str = response.body().string();
                    JSONObject jo = new JSONObject(str);
                    int status = jo.getInt("status");
                    String msg = jo.getString("msg");
                    String fid = jo.getString("fid");

                    if (status == 200) {
                        JSONArray ja = jo.getJSONArray("result");
                        List<MyOrderModel> mOrderList = new ArrayList<>();
                        for (int i = 0; i < ja.length(); i++) {
                            mOrderList.add(GsonUtil.jsonToOrderBean(ja.getJSONObject(i).toString()));
                        }
                        mAdapter.setData(mOrderList);
                    } else if (status == 201) {
                        showToast("用户不存在");
                    } else if (status == 100) {
                        showToast("获取列表失败");
                    } else {
                        showToast("获取异常");
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                mRefreshLayout.endRefreshing();
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                mRefreshLayout.endRefreshing();
            }
        });
    }

    @Override
    public boolean onBGARefreshLayoutBeginLoadingMore(BGARefreshLayout refreshLayout) {
        if (((Boolean) refreshLayout.getTag()) == true) {
            return false;
        }
        mEngine.loadOrderList(userModel.getUser_id(), MD5.getMessageDigest((Constants.BASE_KEY + userModel.getUser_id()).getBytes()), String.valueOf(mCurrentPage + 1), pageCount).enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    String str = response.body().string();
                    JSONObject jo = new JSONObject(str);
                    int status = jo.getInt("status");
                    String msg = jo.getString("msg");
                    String fid = jo.getString("fid");

                    if (status == 200) {
                        mCurrentPage++;
                        JSONArray ja = jo.getJSONArray("result");
                        List<MyOrderModel> mOrderList = new ArrayList<>();
                        for (int i = 0; i < ja.length(); i++) {
                            mOrderList.add(GsonUtil.jsonToOrderBean(ja.getJSONObject(i).toString()));
                        }
                        mAdapter.addMoreData(mOrderList);
                    } else if (status == 201) {
                        showToast("用户不存在");
                    } else if (status == 100) {
                        showToast("获取列表失败");
                    } else {
                        showToast("获取异常");
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                mRefreshLayout.endLoadingMore();
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                mRefreshLayout.endLoadingMore();
            }
        });
        return true;
    }


}
